package ValidText;

import Zeze.Net.AsyncSocket;
import Zeze.Serialize.ByteBuffer;
import Zeze.Util.Task;

import java.nio.charset.StandardCharsets;
import java.util.Properties;

public class ValidTextProtocol {
    private final AsyncSocket sender;
    private final Properties properties;

    public ValidTextProtocol(AsyncSocket sender, Properties properties) {
        this.sender = sender;
        this.properties = properties;
    }

    public static void decode(AsyncSocket sender, ByteBuffer input) {
        var pEndIndex = findProtocolEnd(input);
        if (pEndIndex >= 0) {
            var lineIndex = input.ReadIndex;
            var properties = new Properties();
            while (true) {
                lineIndex = findLine(input, lineIndex, pEndIndex);
                // 这里使用trim删除尾部换行"\r\n"效率不高。
                var text = new String(input.Bytes, input.ReadIndex, lineIndex - input.ReadIndex, StandardCharsets.UTF_8).trim();
                if (text.isEmpty())
                    break;
                var nv = text.split(":");
                if (nv.length == 2) {
                    properties.put(nv[0], nv[1]);
                }
            }
            var protocol = new ValidTextProtocol(sender, properties);
            Task.run(protocol::process, "ValidText.Process");
            input.ReadIndex = pEndIndex; // 已经处理的。
        }
    }

    public static int findLine(ByteBuffer input, int offset, int endIndex) {
        for (var i = offset; i < endIndex; ++i) {
            if (input.Bytes[i] == '\n')
                return i + 1;
        }
        return -1;
    }

    public static int findProtocolEnd(ByteBuffer input) {
        var end = input.WriteIndex;
        for (var p = input.ReadIndex; p < end; /* none */) {
            if (input.Bytes[p] == '\r' && (p + 1) < end && input.Bytes[p + 1] == '\n') {
                p += 2;
                if (p < end && input.Bytes[p] == '\r' && (p + 1) < end && input.Bytes[p + 1] == '\n') {
                    return p + 2; // 返回头部结束的位置
                }
            } else if (input.Bytes[p] == '\n') {
                p++;
                if (p < end && input.Bytes[p] == '\n') {
                    return p + 1; // 返回头部结束的位置
                }
            } else {
                p++;
            }
        }
        return -1;
    }

    private void process() {

    }

}
